#include "AnimateMeshSceneNode.h"

namespace ISNW
{
namespace scene
{
	void AnimateMeshSceneNode::onAnimate(u32 Time)
	{
		if(!isVisible) return;

		buildCurrFrame(Time);

		AnimateMesh->animate(currFrame);

		ISceneNode::onAnimate(Time);
	}

	void AnimateMeshSceneNode::buildCurrFrame(u32 Time)
	{
		u32 time_escaped = Time - lastTime;
		if(time_escaped * FPS >= 1000)
		{
			currFrame++;
			if(currFrame > totalFrame)
			{
				switch(AnimateType)
				{
				case E_AT_LINEAR:
					currFrame = totalFrame;
					break;
				case E_AT_LOOP:
					currFrame = 0;
					break;
				}
			}
		}
	}

	void AnimateMeshSceneNode::render()
	{
		if(isVisible)
		{
			if(AnimateMesh)
			{
				if(scenemanager)
				{
					u32 count = AnimateMesh->getmeshbuffercount();
					for(u32 i = 0; i < count; ++i)
					{
						IMeshBuffer* ibuffer = AnimateMesh->getmeshbuffer(i);
						MeshBuffer* buffer = static_cast<MeshBuffer*>(ibuffer);

						core::array<u16> index_buffer;
						for(u32 k = 0; k < buffer->indices_buffer.size(); ++k)
						{
							index_buffer.push_back((u16)(buffer->indices_buffer[k]));
						}

						scenemanager->getdriver()->setTransform(video::E_WORLD,AbsoluteTransformation);

						scenemanager->getdriver()->setmaterial(buffer->m_material);

						scenemanager->getdriver()->drawtriangles(buffer->vertex_buffer.pointer(),video::STANDAND_VERTEX,buffer->vertex_buffer.size(),index_buffer.pointer(),buffer->indices_buffer.size()/3);

					}
				}
			}
		}
	}

	void AnimateMeshSceneNode::onRegisterSceneNode()
	{
		if(isVisible)
		{
			if(AnimateMesh)
			{
				if(scenemanager)
				{
					scenemanager->registernodeforrendering(this,E_RT_SOLID);
				}
			}
		}
	}

} // end namespace scene
} // end namespace ISNW